package com.redis.example.config;

import com.redis.example.recv.RedisReceiver;
import com.redis.example.recv.RedisRecv;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * @Author: liuchengcheng
 * @Date: 2021/10/25 10:39
 */
@Configuration
@EnableCaching
public class RedisConfig {

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter adapter){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(adapter,new PatternTopic("channel:test"));
        return container;
    }
    @Bean
    MessageListenerAdapter adapter(RedisReceiver receiver){
        return new MessageListenerAdapter(receiver, "onMessage");
    }

    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        //实例化RedisTemplate类
        return new StringRedisTemplate(connectionFactory);
    }
}
